﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;
using System.Data.Linq;
public class GenMenu
{
    

    public static void WriteXML_R(string fileName)
    {
        XmlTextWriter w = new XmlTextWriter(new StreamWriter(new FileStream(fileName, FileMode.Create)));
        
        w.WriteStartElement("ul");
        w.WriteAttributeString("ID", "nav");

        MenuDataContext mn = new MenuDataContext();
        IEnumerable<TMenu> menus = from m in mn.TMenus where m.levelID == 1 select m;

        WriteXML(w, menus, mn);

        w.WriteEndElement();
        w.Close();
    }
    public static void WriteXML(XmlTextWriter w, IEnumerable<TMenu> menus, MenuDataContext mn)
    {
        foreach (TMenu menu in menus)
        {
            int level = Int32.Parse(menu.levelID.ToString());
            int parentID = Int32.Parse(menu.itemID.ToString());
            IEnumerable<TMenu> childMenu = from m in mn.TMenus where (m.levelID == level + 1 && m.parentID == parentID) select m;
            w.WriteStartElement("li");
            w.WriteStartElement("a");
            w.WriteAttributeString("href", menu.url);
            w.WriteString(menu.itemText);
            w.WriteEndElement();    // </a>
            if (childMenu.Count() > 0)
            {
                w.WriteStartElement("ul");

                WriteXML(w, childMenu, mn);

                w.WriteEndElement();
            }
            w.WriteEndElement();    // </li>
        }
    }
    public static string ReadXMLContent(string fileName)
    {
        StreamReader r = new StreamReader(fileName);
        string s = r.ReadToEnd();
        r.Close();
        return s;
    }
}
